// pages/daka/clockIn/clockIn.js
var util = require('../../../utils/utils.js');

Component({
  /**
   * 组件的初始数据
   */
  data: {
    //输出<
    char_lt: "<",
    openid: "",
    //表单数据
    bloodSugar: '', //血糖
    sugarError: '',
    bloodFat: '', //血脂
    fatError: '',
    bloodPressure1: '', //血压
    pressureError1: '',
    pressure1visible1: false,
    pressure1visible2:false,
    sugarvisible: false,
    fatvisible: false,
    creatininevisible:false,
    uricProteinvisible:false,
    uricGravityvisible:false,
    uricpHvisible:false,
    uricVolumevisible:false,
    colorvisible:false,
    bloodPressure2: '', //血压
    pressureError2: '',
    color: '', //尿液颜色
    uricColorError:'',//颜色校验
    uricProtein: '', //尿蛋白
    uricProteinError:'',//尿蛋白校验
    uricGravity:'',//尿比重
    uricGravityError:'',//尿比重校验
    uricpH:'',//尿ph
    uricpHError:'',//尿pH
    uricVolume:'',//尿量
    uricVolumeError:'',//尿量校验
    creatinine: '', //肌酐
    creatinineError: '',//肌酐校验
    result: [],
    others: '',
    radio: '',
    //pop
    popupshow: false,
    //cardwarp
    cardwarpColor:[
      '#067C89',
      '#089BAB',
      '#6BC3CD',
      '#84CDD5'
    ],
    //第四页数据
    alcohol:-1,
    diet:-1,
    emotion:-1,
    sleep:-1,
    sport:-1,

    //页面动画
    allPageCount: 4,
    allPageCount2:[
      {color:'#067C89',
      name:'第一页'
    },
    {color:'#089BAB',
      name:'第二页'
    },
    {color:'#6BC3CD',
    name:'第三页'
  },
  {color:'#84CDD5',
    name:'第四页'
  },

],
    currPage: 0,
    animationData: {},
    //txt
    lastString: "上一项",
    nextString: ""
  },
  /**
   * 组件的生命周期
   */
  lifetimes: {
    created: function () {
      //获取用户id
      this.getOpenid()
    },
    attached: function () {
    },
    detached: function () {
      // 在组件实例被从页面节点树移除时执行
    },
  },
  /**
   * 组件的属性列表
   */
  properties: {
    pressure1visible1:false
  },


  /**
   * 组件的方法列表
   */
  methods: {
    //reset
    delbtnre() {
      console.log("??????")
      this.setData({
        bloodSugar: '', //血糖
        sugarError: '',
        bloodFat: '', //血脂
        fatError: '',
        bloodPressure1: '', //血压
        pressureError1: '',
        bloodPressure2: '', //血压
        pressureError2: '',
      })
    },
    delbtnre3() {
      this.setData({
        color: '', //尿液颜色
        uricColorError:'',//颜色校验
        uricProtein: '', //尿蛋白
        uricProteinError:'',//尿蛋白校验
        uricGravity:'',//尿比重
        uricGravityError:'',//尿比重校验
        uricpH:'',//尿ph
        uricpHError:'',//尿pH
        uricVolume:'',//尿量
        uricVolumeError:'',//尿量校验
        creatinine: '', //肌酐
        creatinineError: '',//肌酐校验
      })
    },
    //OnTap
    onTapIcon(index){
      console.log(index)
      console.log(this.data)
      switch (index.target.dataset.index) {
         case '1':
           this.setData({
            pressure1visible1:!this.data.pressure1visible1
           })
           console.log(this.data.pressure1visible1)
           break;
        case '2':
           this.setData({
            pressure1visible2:!this.data.pressure1visible2
           })
           break;
        case '3':
            this.setData({
              sugarvisible:!this.data.sugarvisible
            })
            break;
        case '4':
              this.setData({
                fatvisible:!this.data.fatvisible
              })
              break;
        case '5':
                this.setData({
                  uricProteinvisible:!this.data.uricProteinvisible
                })
                break;
        case '6'://肌酐
                this.setData({
                  creatininevisible:!this.data.creatininevisible
                })
                break;
        case '7'://尿比重
                this.setData({
                  uricGravityvisible:!this.data.uricGravityvisible
                })
                break;
        case '8'://尿pH
                this.setData({
                  uricpHvisible:!this.data.uricpHvisible
                })
                break;
        case '9'://尿量
                this.setData({
                  uricVolumevisible:!this.data.uricVolumevisible
                })
                break;
        case '10'://尿液颜色
                this.setData({
                  colorvisible:!this.data.colorvisible
                })
                console.log("???")
                break;
      }
    },

    //重置
    reset() {
      this.setData({
        result: [],
        others:'',
        alcohol:-1,
        diet:-1,
        emotion:-1,
        sleep:-1,
        sport:-1
      })
    },
    onClick(event) {
      this.setData({
        pressure1visible2:!this.data.pressure1visible2
       })
    },
    //选择之后
    onChange(event) {
      this.setData({
        result: event.detail,
      });
    },
    onRadioChange(e){
      var choice = e.detail
      var data = -1
      //几乎都这样
      if(choice=='1')
      data = 1//是
      else
      data = 0//否

      switch(e.currentTarget.id){
        case 'alcohol':
          this.setData({
            // alcohol:data
            alcohol:choice
          })
          break;
        case 'diet':
            this.setData({
              diet:choice
            })
            break;
        case 'emotion':
              this.setData({
                emotion:choice
              })
              break;
        case 'sleep':
                this.setData({
                  sleep:choice
                })
                break;
        case 'sport':
                  this.setData({
                    sport:choice
                  })
                  break;
      }
      console.log(e)
    },
    bindKeyInput: function (e) {
      let id = e.target.id;
      if (id == 'fat') {
        if (!FatDetect(e.detail)) { //校验失败
          this.setData({
            fatError: "输入格式不正确(0.0-20.0)"
          })
        } else {
          this.setData({
            fatError: '',
            bloodFat: e.detail
          })
        }
      } else if (id == 'sugar') {
        if (!SugarDetect(e.detail)) { //校验失败
          this.setData({
            sugarError: "输入格式不正确(0.0-20.0)"
          })
        } else {
          this.setData({
            sugarError: '',
            bloodSugar: e.detail
          })
        }
      } else if (id == "pressure1") {
        console.log(PressureDetect(e.detail))
        if (!PressureDetect(e.detail)) { //校验失败
          this.setData({
            pressureError1: "输入格式不正确(0-300)"
          })
        } else {
          this.setData({
            pressureError1: '',
            bloodPressure1: e.detail
          })
        }
      } else if (id == "pressure2") {
        if (!PressureDetect(e.detail)) { //校验失败
          this.setData({
            pressureError2: "输入格式不正确(0-300)"
          })
        } else {
          this.setData({
            pressureError2: '',
            bloodPressure2: e.detail
          })
        }
      } else if (id == "color") {
        this.setData({
          color: e.detail
        })
      } else if (id == "uricProtein") {//尿蛋白
        if (!UricProteinDetect(e.detail)) { //校验失败
          this.setData({
            uricProteinError: "输入格式不正确(0-300mg)"
          })
        } else {
          console.log(typeof(e.detail))
          this.setData({
            uricProteinError:'',
            uricProtein: e.detail
          })
          console.log(this.data.uricProtein)
        }
      } else if (id == "creatinine") {//肌酐
        if (!CreatinineDetect(e.detail)) { //校验失败
          this.setData({
            creatinineError: "输入格式不正确(0-300μmol/L)"
          })
        } else {
          this.setData({
            creatinineError: '',
            creatinine: e.detail
          })
        }
      }else if (id == "uricGravity") {//尿比重
        if (!UricGravityDetect(e.detail)) { //校验失败
          this.setData({
            uricGravityError: "输入格式不正确(1.000-1.030)"
          })
        } else {
          this.setData({
            uricGravityError: '',
            uricGravity: e.detail
          })
        }
      }else if (id == "uricpH") {//尿比ph
        if (!UricpHDetect(e.detail)) { //校验失败
          this.setData({
            uricpHError: "输入格式不正确(0.0-10.0)"
          })
        } else {
          this.setData({
            uricpHError: '',
            uricpH: e.detail
          })
        }
      }else if (id == "uricVolume") {//尿量
        if (!UricVolumeDetect(e.detail)) { //校验失败
          this.setData({
            uricVolumeError: "输入格式不正确(0-10000ml)"
          })
        } else {
          this.setData({
            uricVolumeError: '',
            uricVolume: e.detail
          })
        }
      }
    },
    //获取屏幕长宽
    getCurrScreeSize() {
      // 获取系统信息
      wx.getSystemInfo({
        success: function (res) {
          // 获取可使用窗口宽度
          let clientHeight = res.windowHeight;
          // 获取可使用窗口高度
          let clientWidth = res.windowWidth;
          // 算出比例
          let ratio = 750 / clientWidth;
          // 算出高度(单位rpx)
          let height = clientHeight * ratio;
          // 设置高度
          that.setData({
            height: height
          });
        }
      });

    },
    getOpenid: function () {
      wx.cloud.callFunction({
        name: 'getOpenId',
        complete: res => {
          wx.setStorageSync('openid', res.result.openid)
          this.setData({
            openid: res.result.openid
          })
        }
      })
    },
    slidethis: function (e) {
      var id = e.currentTarget.dataset.id
      // 创建一个animation  
      var animation = wx.createAnimation({
        duration: 300,
        timingFunction: 'cubic-bezier(.8,.2,.1,0.8)',
      });
      var self = this;
      this.animation = animation;
      this.animation.translateY(-420).rotate(-5).translateX(0).step();
      this.animation.translateY(0).translateX(0).rotate(0).step();
      this.setData({
        animationData: this.animation.export()
      });
      //动画结束事件
      setTimeout(function () {
        self.setData({
          currPage: id,
          animationData: {}
        });
      }, 350);
    },
    slidethis2: function (index,that) {
      var id = index
      // 创建一个animation  
      var animation = wx.createAnimation({
        duration: 300,
        timingFunction: 'cubic-bezier(.8,.2,.1,0.8)',
      });
      var self = that;
      that.animation = animation;
      that.animation.translateY(-420).rotate(-5).translateX(0).step();
      that.animation.translateY(0).translateX(0).rotate(0).step();
      self.setData({
        animationData: that.animation.export()
      });
      //动画结束事件
      setTimeout(function () {
        self.setData({
          currPage: id,
          animationData: {}
        });
      }, 350);
    },
    //提交数据
    submitPage1: function () {
      wx.showLoading({
        title: '正在加载',
        mask: true
      })
      if (this.data.bloodSugar.length == 0 && this.data.bloodPressure1.length == 0 && this.data.bloodPressure2.length == 0) {
        wx.showToast({
          title: '您还未填入数据！',
          icon: 'error',
          duration: 1000
        })
      } else {
        wx.cloud.callFunction({
          name: "clockIn",
          data: {
            type: "addDaka",
            openid: wx.getStorageSync('openid'),
            bloodSugar: this.data.bloodSugar,
            // bloodFat: this.data.bloodFat,
            bloodPressure1: this.data.bloodPressure1,
            bloodPressure2: this.data.bloodPressure2

          }
        }).then(res => {
          setTimeout(function () {
            wx.hideLoading()
          }, 0)
          wx.showToast({
            title: '打卡成功',
            icon: 'success',
            duration: 1000
          })
          console.log(res)
          var index = 1
          this.__proto__.slidethis2(index,this)
        }).catch(res => {
          setTimeout(function () {
            wx.hideLoading()
          }, 0)
          wx.showToast({
            title: '打卡失败',
            icon: 'error',
            duration: 1000
          })
          console.log('error!')
          console.log(res)
        })
      }
    },
    submitPage2: function () {
      var result = this.data.result
      var string = ""
      result.forEach(element => {
        string += element + ";"
      });
      if (this.data.others == '' && string == '') {
        wx.showToast({
          title: '您还未填入数据！',
          icon: 'error',
          duration: 1000
        })
      } else {
        wx.showLoading({
          title: '正在加载',
          mask: true
        })
        wx.cloud.callFunction({
          name: "clockIn",
          data: {
            type: "addDaka",
            openid: wx.getStorageSync('openid'),
            result: string,
            other: this.data.other
          }
        }).then(res => {
          wx.showToast({
            title: '打卡成功',
            icon: 'success',
            duration: 1000
          })
          console.log(res)
          var index = 2
          this.__proto__.slidethis2(index,this)
        }).catch(res => {
          wx.showToast({
            title: '打卡失败',
            icon: 'error',
            duration: 1000
          })
          console.log('error!')
          console.log(res)
        })
      }
    },
    submitPage3: function () {
      if (this.data.color.length == 0 && this.data.uricProtein.length == 0 && this.data.creatinine.length == 0) {
        wx.showToast({
          title: '您还未填入数据！',
          icon: 'error',
          duration: 1000
        })
      } else {
        wx.showLoading({
          title: '正在加载',
          mask: true
        })
        wx.cloud.callFunction({
          name: "clockIn",
          data: {
            type: "addDaka",
            openid: wx.getStorageSync('openid'),
            color: this.data.color,//颜色
            uricProtein: this.data.uricProtein,//尿蛋白
            creatinine: this.data.creatinine,//肌酐
            uricVolume: this.data.uricVolume,//尿量
            uricpH: this.data.uricpH,//尿ph
            uricGravity: this.data.uricGravity,//尿比重
          }
        }).then(res => {
          wx.showToast({
            title: '打卡成功',
            icon: 'success',
            duration: 1000
          })
          console.log(res)
          var index = 3
          this.__proto__.slidethis2(index,this)
        }).catch(res => {
          wx.showToast({
            title: '打卡失败',
            icon: 'error',
            duration: 1000
          })
          console.log('error!')
          console.log(res)
        })
      }
    },
    //TODO:修改逻辑调用俩数据库啊
    submitPage4: function () {
      if (this.data.alcohol == -1 && this.data.diet == -1 && this.data.emotion == -1 && this.data.sleep==-1 && this.data.sport == -1) {

        wx.showToast({
          title: '您还未填入数据！',
          icon: 'error',
          duration: 1000
        })
      } else {
        wx.showLoading({
          title: '正在加载',
          mask: true
        })
        console.log(wx.getStorageSync('openid'));
        wx.cloud.callFunction({
          name: "clockIn",
          data: {
            type: "addDaka",
            openid: wx.getStorageSync('openid'),
            alcohol:this.data.alcohol,
            diet:this.data.diet,
            emotion:this.data.emotion,
            sleep:this.data.sleep,
            sport:this.data.sport
          }
        }).then(res => {
         var records = wx.cloud.callFunction({
           name: "clockIn",
           data: {
              type: "getRecords",
              openid: wx.getStorageSync('openid'),
            },
         }).then(res=>{
           var _totalday = res.result.records.length
           var _records = res.result.records//这里是所有的记录
          //  console.log(totalday)
          wx.cloud.callFunction({
            name: "clockIn",
            data: {
              type: "addRecords",
              openid: wx.getStorageSync('openid'),
              records:_records,
              totalday:_totalday
            }
          }).then(res => {
            console.log("更新成功")
          })
         })

          wx.showToast({
            title: '打卡成功',
            icon: 'success',
            duration: 1000,
          })
          // success:res=>{
          //   this.triggerEvent('switchToCalendar')
          // }
          var that = this
          setTimeout(function(){that.triggerEvent('switchToCalendar')},1100)
          console.log(res)
        }).catch(res => {
          wx.showToast({
            title: '打卡失败',
            icon: 'error',
            duration: 1000
          })
          console.log('error!')
          console.log(res)
        })
      }
    },
    triggerCalendar(that){
      that.triggerEvent('switchToCalendar')
    }
  }
})
//校验尿量
function UricVolumeDetect(value){
  var num = /^(\d?)+(\.\d{0,1})?$/; //全数字
  if (!num.exec(value)) {
    console.log("???")
    return false;
  }
  var pressure = parseFloat(value)
  if (pressure > 10000 || pressure < 0) {
    return false;
  }
  return true
}
//校验尿ph
function UricpHDetect(value){
  var num = /^(\d?)+(\.\d{0,1})?$/; //小数
  if (!num.exec(value)) {
    console.log("???")
    return false;
  }
  var sugar = parseFloat(value)
  if (sugar > 10.0 || sugar < 0) {
    return false;
  }
  return true
}
//校验尿比重
function UricGravityDetect(value){
  var num = /^(\d{0,1})+(\.\d{0,3})?$/; //小数
  if (!num.exec(value)) {
    console.log("???")
    return false;
  }
  var sugar = parseFloat(value)
  if (sugar > 1.030 || sugar < 1.000) {
    return false;
  }
  return true
}
//校验尿蛋白
function UricProteinDetect(value){
  return PressureDetect(value)
}
//校验肌酐
function CreatinineDetect(value){
  return PressureDetect(value)
}
function SugarDetect(value) {
  var num = /^(\d?)+(\.\d{0,1})?$/; //小数
  var num2 = /^(\d?)+(\.\d{0,2})?$/; //小数
  if (!num.exec(value)&&!num2.exec(value)) {
    console.log("???")
    return false;
  }
  var sugar = parseFloat(value)
  if (sugar > 20.0 || sugar < 0) {
    return false;
  }
  return true

}

function FatDetect(value) {
  return SugarDetect(value)

}

function PressureDetect(value) {
  var num = /^(\d?)+(\.\d{0,1})?$/; //全数字
  if (!num.exec(value)) {
    console.log("???")
    return false;
  }
  var pressure = parseFloat(value)
  if (pressure > 300 || pressure < 0) {
    console.log("!!!")
    console.log("???")
    return false;
  }
  return true
}